package com.shaoshaohuo.app.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.utils.city.Cityinfo;
import com.shaoshaohuo.app.entity.Addressinfo;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.UserInfoEntity;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.adapter.OftenAddressListAdapter;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenu;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuCreator;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuItem;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuListView;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuListView.OnMenuItemClickListener;
import com.shaoshaohuo.app.utils.CityinfoUtil;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;
import com.shaoshaohuo.app.view.citymenu.entity.Area;

import java.util.List;

public class OftenAddressActitity extends BaseActivity implements OnClickListener {
	
	
	private Cityinfo mCity; //开始的市


	private TopbarView mTopbarView;
	
	private SwipeMenuListView mAddressListview;
	
	private View mSaveLayout;
	private Button mSaveButton;
	private CascadingMenuPopWindow cascadingMenuPopWindow;

	private TextView mAddressText;

/*    private Province province;

    private City city;*/

    private OftenAddressListAdapter<Object> mAdapter;

    private List<Addressinfo> addressinfo;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_offen_address);
		initView();
		setUpView();
		requestData();
		
		setResult(RESULT_OK);
	}

	private void requestData() {
	    startLoadingDialog();
        RequestService.getInstance().getUserInfo(this, UserInfoEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    UserInfoEntity entity = (UserInfoEntity) resultData;
                    setAdapter(entity);
                }else{
                    showToast(resultData.getMsg());
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
	}
	
    protected void setAdapter(UserInfoEntity entity) {
        addressinfo = entity.getData().getAddressinfo();
        if(mAdapter == null){
            mAdapter = new OftenAddressListAdapter<>(this, addressinfo, false);
            mAddressListview.setAdapter(mAdapter);
        }else{
            mAdapter.setData(addressinfo);
        }
    }

    private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mAddressListview = (SwipeMenuListView) this.findViewById(R.id.listview_address_list);
		mSaveLayout = this.findViewById(R.id.layout_save);
		mSaveButton = (Button) this.findViewById(R.id.button_save);
		
		mAddressText = (TextView) this.findViewById(R.id.textview_address);
	}
	
	private void setUpView() {
		mTopbarView.setCenterText("常居地");
		mTopbarView.setLeftView(true, true);
		mTopbarView.setRightText("添加");
		mTopbarView.setRightClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mSaveLayout.setVisibility(mSaveLayout.getVisibility() == View.VISIBLE?View.GONE:View.VISIBLE);
			}
		});

		
		SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.parseColor("#FF6368")));
                // set item width
                deleteItem.setWidth(StringHelper.dip2px(OftenAddressActitity.this,50));
                // set a icon
                deleteItem.setIcon(R.drawable.icon_delete);
                
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        // set creator
        mAddressListview.setMenuCreator(creator);
        
        mAddressListview.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                Addressinfo address = addressinfo.get(position);
                showDialog("確定刪除 "+address.getCityname()+"?", address.getId());
                return false;
            }
        });
		
		mSaveLayout.setVisibility(View.GONE);
		
		mAddressText.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				/*Intent intent = new Intent(OftenAddressActitity.this,SelectProvinceActivity.class);
				startActivityForResult(intent, 0);*/
				
				showDialog();
				
			}
		});
		
		
		mSaveButton.setOnClickListener(this);
	}
	
	
	
	/**
	 * 显示开始
	 */
	private void showDialog() {
		/*AlertDialog.Builder builder = new Builder(OftenAddressActitity.this);
		// builder.setView(R.layout.activity_hello);
		View inflate = View.inflate(getBaseContext(), R.layout.sanji, null);
		cityPicker = (CityPicker) inflate.findViewById(R.id.citypicker);
		cityPicker.setOnSelectingListener(new OnSelectingListener() {
			@Override
			public void selected(boolean selected) {
			
			}
		});
		builder.setView(inflate);
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				//TODO
				mProvince = cityPicker.getprovince();
				mCity = cityPicker.getCity();
				mAddressText.setText(mCity.getCity_name());
				
			}

		
		});
		builder.show();*/
		if (cascadingMenuPopWindow == null) {
			//向三级menu添加地区数据
			cascadingMenuPopWindow = new CascadingMenuPopWindow(this, false);
			cascadingMenuPopWindow
					.setMenuViewOnSelectListener(new NMCascadingMenuViewOnSelectListener());
			cascadingMenuPopWindow.showAsDropDown(mAddressText, 5, 5);
		} else if (cascadingMenuPopWindow != null
				&& cascadingMenuPopWindow.isShowing()) {
			cascadingMenuPopWindow.dismiss();
		} else {
			cascadingMenuPopWindow.showAsDropDown(mAddressText, 5, 5);
		}
	}
	 // 级联菜单选择回调接口
 	class NMCascadingMenuViewOnSelectListener implements
 			CascadingMenuViewOnSelectListener {

 		@Override
 		public void getValue(Area city, String fullname) {
 			mAddressText.setText(fullname);
 			mCity = CityinfoUtil.convert(city);
 		}

 	}
	
	
/*	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
	    super.onActivityResult(arg0, arg1, arg2);
	    if(arg1 == RESULT_OK && arg2 != null){
	        province = (Province) arg2.getSerializableExtra(ExtraName.province);
	        city = (City) arg2.getSerializableExtra(ExtraName.city);
	        
	        mAddressText.setText(city.getCityname());
	        
        }
	}*/
	
	private void showDialog(String message, final String id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteAddress(id);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }
	
	private void deleteAddress(String id){
	    startLoadingDialog();
	    RequestService.getInstance().deleteReside(this, id, BaseEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    showToast("刪除成功");
                    mSaveLayout.setVisibility(View.GONE);
                    requestData();
                }else{
                    showToast(resultData.getMsg());
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
	}
	
	private void addAddress(String cityid) {
		startLoadingDialog();
		RequestService.getInstance().addOftenAddress(this, cityid, BaseEntity.class, new RequestListener() {
			
			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if(resultData.isOk()){
				Log.e("服务器返回：", resultData.toString());
				   showToast("添加成功");
//				   mSaveLayout.setVisibility(View.GONE);
				   mAddressText.setText("选择地址");
				 /*  province = null;
				   city = null;*/
				   mCity = null;
				   requestData();
				}else{
				    showToast(resultData.getMsg());
				}
			}
			
			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button_save:
           /* if(province == null || city==null){
                showToast("请选择地址");
                return;
            }
            addAddress(province.getProid(), city.getCitycode());*/
        	
        	if(mCity == null)
        	{
        		showToast("请选择地址");
        		return ;
        	}
        	//Log.e("mProvince.getId(), mCity.getCitycode()", mProvince.getId()+"..."+ mCity.getCitycode());
            addAddress(mCity.getId());
            break;
        }
    }
    @Override
	protected void onDestroy() {
		if (cascadingMenuPopWindow != null) {
			cascadingMenuPopWindow.dismiss();
		}
		super.onDestroy();
	}
}
